<?php
namespace waf\client\rpc;

use \waf\Waf;
use \waf\log\WLog;

class WRpcClient
{
    /**
     * 转换成rpc的参数形式
     *
     * @param array $arrParams
     * @return string
     */
    protected static function getRpcParams($arrParams = array())
    {
        $strRet = '';
        WLog::logDebug("arrParams = ". WLog::toJson($arrParams), __FILE__, __LINE__, __FUNCTION__);

        $arrParams['seq']   = self::getWorkerGlobalSeq();
        $strRet = WLog::toJson($arrParams);

        WLog::logDebug("strRet = {$strRet}", __FILE__, __LINE__, __FUNCTION__);
        return $strRet;
    }

    /**
     * 获取本Worker进程的全局seq
     *
     * @return int
     */
    protected static function getWorkerGlobalSeq()
    {
        $intRet = 0;
        return $intRet;
    }

    protected static function doSendData($rpc_type = '', $conf  = array(),  $arrParams  = array())
    {
        $arrRet = array('r' => 0, 'data'    => array());

        $client = new \Swoole\Coroutine\Client($rpc_type);
        if (!$client->connect($conf['ip'], $conf['port'], 0.5))
        {
            $arrRet['r']    = 10000;
            WLog::logError("connect failed. Error: {$client->errCode}", __FILE__, __LINE__, __FUNCTION__);
        }else{
            $client->send(self::getRpcParams($arrParams));
            $arrRet['data']    = $client->recv();
            $client->close();
        }

        return $arrRet;
    }

    public static function doSendUdpData($conf  = array(),  $arrParams  = array())
    {
        return self::doSendData(SWOOLE_SOCK_UDP, $conf, $arrParams);
    }

    public static function doSendTcpData($conf  = array(),  $arrParams  = array())
    {
        return self::doSendData(SWOOLE_SOCK_TCP, $conf, $arrParams);
    }

    //=================== 正常版本 tcp , udp
    /**
     * 发送正常udp包
     *
     * @param $conf
     * @param $arrParams
     * @return bool
     */
    public static function sendNormalUdpData($conf, $arrParams)
    {
        $socket = stream_socket_client("udp://{$conf['ip']}:{$conf['port']}", $errno, $errstr);
        if(!$socket)
        {
            return false;
        }
        $buffer = self::getRpcParams($arrParams);
        return stream_socket_sendto($socket, $buffer) == strlen($buffer);
    }
}
?>
